import {Dimensions, PixelRatio} from "react-native";

import {storage} from "../utils/storage";
import tool from "../utils/tool";
import pinyin4js from '../utils/pinyin4js';

import {options} from "../Global";

export const onLayout = (event) => {
    //使用大括号是为了限制let结构赋值得到的变量的作用域，因为接来下还要结构解构赋值一次
    {
        //获取根View的宽高，以及左上角的坐标值
        let {x, y, width, height} = event.nativeEvent.layout;
        // console.log('通过onLayout得到的宽度：' + width);
        // console.log('通过onLayout得到的高度：' + height);

        options.window.width = width;
        options.window.height = height;
    }

    //通过Dimensions API获取屏幕宽高
    let {width, height} = Dimensions.get('window');
    // console.log('通过Dimensions得到的宽度：' + width);
    // console.log('通过Dimensions得到的高度：' + height);

    // console.log('字体缩放', PixelRatio.getFontScale());
    // console.log('像素密度', PixelRatio.get());
};

/**
 * 从本地存储里面加载书架列表
 * @returns {Promise<R>}
 */
export const loadBooksFromStorage = () => {
    return new Promise((resolve, reject) => {
        storage.getAllDataForKey('books')
            .then(books => {
                for (let i in books) {
                    let pinyin = PinyinHelper.convertToPinyinString(books[i].title, '', PinyinFormat.WITH_TONE_MARK);
                    books[i].pinyin = pinyin;
                }
                tool.sortChinese(books, 'pinyin');

                let obj = {};
                for (let i in books) {
                    let book = books[i];
                    if (!obj[book.title]) {
                        obj[book.title] = [];
                    }
                    obj[book.title].push(book);
                }
                let arr = [];
                for (let key in obj) {
                    let o = {};
                    o.title = key;
                    o.array = obj[key];
                    arr.push(o);
                }
                resolve({books, arr})
            })
            .catch(err => {
                reject(err);
            })
        ;
    });
};

export const loadGlobalOptionsFromStorage = () => {
};